package ran.handler;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ran.entity.Result;
import ran.enums.ResultCode;
import ran.exception.ServiceException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-10-03
 * Time: 22:27
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<?> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                         HttpServletRequest request) {
        String requestURI = request.getRequestURI();
 log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return Result.fail(ResultCode.ERROR);
    }

    // 处理一些业务层面的异常
    @ExceptionHandler(ServiceException.class)
    public Result<?> handleRuntimeException(ServiceException e, HttpServletRequest request) {
        ResultCode resultCode = e.getResultCode();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}', 业务发生异常:{}, e:", requestURI, resultCode.getMsg(),e);
        return Result.fail(resultCode);
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> handleRuntimeException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("请求地址'{}', 业务发生异常:{}, e:", requestURI, defaultMessage,e);
        return Result.fail(defaultMessage);
    }

    /**
     * UnexpectedTypeException
     * 拦截运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生异常.", requestURI, e);
        return Result.fail(ResultCode.ERROR);
    }
    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生异常.", requestURI, e);
        return Result.fail(ResultCode.ERROR);
    }
}
